package com.frx.datastruct.chaptereleven;

/**
 * Created by xurenfeng on 2019/3/14.
 */
public class UnionFind4 implements UF{
    private int[] parent;
    private int[] rank;

    public UnionFind4(int size){

        parent = new int[size];
        rank = new int[size];
    }

    private int find(int p){

        if (p < 0 || p >= parent.length){
            throw new IllegalArgumentException(" p is out of bound !");
        }
        while ( p != parent[p]){
            p = parent[p];
        }
        return p;
    }
    @Override
    public int getSize() {
        return parent.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {

        int pRoot = find(p);
        int qRoot = find(q);

        if (qRoot == pRoot){
            return;
        }

        if (rank[pRoot] > rank[qRoot]){
            parent[qRoot] = pRoot;
        } else if (rank[pRoot] < rank[qRoot]){
            parent[pRoot] = qRoot;
        } else {
            parent[qRoot] = pRoot;
            // 维护rank的值
            rank[pRoot] += 1;
        }

    }
}
